package com.stars.empoly.update.service

import android.app.*
import android.content.*
import android.os.Binder
import android.os.IBinder
import android.view.View
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.google.gson.Gson
import com.liulishuo.filedownloader.BaseDownloadTask
import com.stars.empoly.App
import com.stars.empoly.update.bean.UpdateBean
import com.stars.empoly.update.util.ApkInstallUtil
import com.stars.empoly.update.util.FileDownLoadUtils
import com.stars.empoly.update.util.Utils
import com.stars.empoly.update.util.downloadFile
import com.stars.empoly.R


import java.io.File


/**
 * 升级下载service
 */
class UpgradeService : Service() {

    private val mUpgradeBinder = UpgradeBinder()

    companion object{
        const val mChannelID = "upgrade002"

        const val NOTICATION_REQUEST_CODE = 0X300

        fun startService(context:Context?,apkPath:String,upgradeData : UpdateBean){
            context?.let{
                val intent = getIntent(it, apkPath, upgradeData)
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    it.startForegroundService(intent);
                } else {
                    it.startService(intent);
                }
            }
        }

        fun bindService(context:Context?, apkPath:String, upgradeData : UpdateBean, conn: ServiceConnection){
            context?.let{
                (it as? LifecycleOwner)?.lifecycle?.addObserver(object:LifecycleObserver{
                    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                    fun onDestory(){
                        it.unbindService(conn)
                    }
                })
                val intent = getIntent(it, apkPath, upgradeData)
                it.bindService(intent,conn,Context.BIND_AUTO_CREATE)
            }
        }

        private fun getIntent(context:Context,apkPath:String,upgradeData : UpdateBean) : Intent {
            return Intent(context, UpgradeService::class.java).apply {
                    this.putExtra("apkPath",apkPath)
                    this.putExtra("upgradeData", Gson().toJson(upgradeData))
            }
        }
    }

    lateinit var onUpgradeProgress:(totalBytes:Int,soFarBytes:Int,progress:Int) -> Unit

    lateinit var onUpgradeComplete:() -> Unit

    lateinit var onUpgradeError:() -> Unit

    private lateinit var mApkPath : String
    private lateinit var mUpgradeData : UpdateBean

    private var mDownloadTask: BaseDownloadTask?= null

    /**
     * 是否暂停下载
     */
    private var isPauseDownload = false

    private lateinit var  mNotificationManager: NotificationManager

    private var mUpgradeNotifyId = 1

    private val NOTIFICATION_PAUSE_CLICK_ACTION = "com.midland.mrapp.pause.click"


    override fun onBind(intent: Intent?): IBinder? {
        initIntent(intent)
        initNotifycation()
        return mUpgradeBinder
    }

    override fun onCreate() {
        super.onCreate()
        initNotifycation()
    }

    private fun initNotifycation(){
        mNotificationManager =App.getApp()?.applicationContext?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //适配8.0service
            val mChannel = NotificationChannel(
                mChannelID,
                Utils.getAppName(this),NotificationManager.IMPORTANCE_HIGH)
            mNotificationManager.createNotificationChannel(mChannel)
            val notification: Notification = Notification.Builder(applicationContext, mChannelID).build()
            startForeground(mUpgradeNotifyId, notification)
        }
    }

    private fun initIntent(intent: Intent?){
        intent?.apply {
            mApkPath = this.getStringExtra("apkPath").toString()
            //获取升级的实体类
            var data =this.getStringExtra("upgradeData")
            mUpgradeData = Gson().fromJson(data, UpdateBean::class.java)

        }
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val startCommand = super.onStartCommand(intent, flags, startId)
        if(startId <= 1){
            initIntent(intent)
            startDownload()
        }
        return START_STICKY
    }

    fun startDownload(){
        mDownloadTask = downloadFile(mUpgradeData.downloadUrl,
            mApkPath,mUpgradeData.version.toString(),
            onCompleted = {
                if(mUpgradeData.isSilentDownload == 1){
                    //静默下载
                    mNotificationManager.cancel(mUpgradeNotifyId)
                    ApkInstallUtil.install(App.getApp()?.applicationContext!!, File(mApkPath))
                    return@downloadFile
                }
                if(::onUpgradeComplete.isInitialized){
                    onUpgradeComplete()
                    stopSelf()
                }
            },
            getProgress = {totalBytes, soFarBytes, progress ->

                if(mUpgradeData.isSilentDownload == 1){
                    //静默下载
                    updateNotifycation(totalBytes, soFarBytes, progress)
                    return@downloadFile
                }
                if(::onUpgradeProgress.isInitialized){
                    onUpgradeProgress(totalBytes, soFarBytes, progress)
                }
            },
            onError = {
                if(mUpgradeData.isSilentDownload == 1){
                    //静默下载
                    isPauseDownload = true
                    val smallFileTotalBytes = mDownloadTask?.smallFileTotalBytes?:0
                    val smallFileSoFarBytes = mDownloadTask?.smallFileSoFarBytes?:0
                    val progress = FileDownLoadUtils.getDownloadProgress(smallFileSoFarBytes,smallFileTotalBytes).toInt()
                    updateNotifycation(smallFileTotalBytes,smallFileSoFarBytes,progress)
                    return@downloadFile
                }
                if(::onUpgradeError.isInitialized){
                    onUpgradeError()
                    stopSelf()
                 }
            })
        mDownloadTask?.start()
    }


    /**
     * 更新通知栏
     */
    private fun updateNotifycation(totalBytes:Int = 0, soFarBytes:Int = 0, progress:Int = 0){
        val contentIntent = PendingIntent.getActivity(this, NOTICATION_REQUEST_CODE,
            Intent(this,this.javaClass).apply {
                addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            },0)

        val remoteView = RemoteViews(packageName, R.layout.layout_notification_download_apk)

        remoteView.setViewVisibility(R.id.progress_layout,View.VISIBLE)
        remoteView.setViewVisibility(R.id.icon_start_btn,View.VISIBLE)
        remoteView.setTextViewText(R.id.tv_title, App.getApp()?.packageName+"版本更新")
        remoteView.setTextViewText(R.id.tv_text, "当前进度${progress}%");
        remoteView.setProgressBar(R.id.progressBar, totalBytes, soFarBytes, false);
        if(!isPauseDownload){
            remoteView.setImageViewResource(R.id.icon_start_btn, R.drawable.icon_download_start)
        }else{
            remoteView.setImageViewResource(R.id.icon_start_btn, R.drawable.icon_download_pause)
        }
        registerReceiver(mOnClickReceiver, IntentFilter().apply {
            this.addAction(NOTIFICATION_PAUSE_CLICK_ACTION)
        })
        remoteView.setOnClickPendingIntent(R.id.icon_start_btn,
            PendingIntent.getBroadcast(this, 0, Intent(NOTIFICATION_PAUSE_CLICK_ACTION), 0))

        val notification = NotificationCompat.Builder(this.applicationContext, mChannelID)
                                                          .setContent(remoteView)
                                                          .setCustomBigContentView(remoteView)
                                                          .setWhen(System.currentTimeMillis())
                                                          .setAutoCancel(false)
                                                          .setSmallIcon(R.mipmap.ic_launcher)
                                                          .setContentIntent(contentIntent)
                                                          .build()
        mNotificationManager.notify(mUpgradeNotifyId,notification)

    }


    inner class UpgradeBinder : Binder() {
        fun getService() : UpgradeService {
            return this@UpgradeService
        }
    }


    val mOnClickReceiver = object:BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent == null) {
                return
            }
            when (intent.action) {
                NOTIFICATION_PAUSE_CLICK_ACTION -> {//暂停下载，开始下载
                    if(!isPauseDownload){
                        isPauseDownload = true
                        mDownloadTask?.pause()
                    }else{
                        isPauseDownload = false
                        mDownloadTask?.reuse()
                        mDownloadTask?.start()
                    }
                }
            }

        }

    }


}
